<template>
  <div id="app" >
    <page-loading v-if="!hasLoadResources"></page-loading>
    <loading v-if="isLoading"></loading>
    <subscribe v-if="subscribe == 0"></subscribe>
    <transition :name="this.routerAni">
      <router-view class="router-view"></router-view>
    </transition>
  </div>
</template>

<script>
import Loader from 'resource-loader'
import { openToast } from '@/assets/js/tools'
// import { popup, openToast, openLoading, closeLoading } from './js/tools'
import pageLoading from '@/components/pageLoading'
import resources from '@/assets/js/resources'
import { mapState } from 'vuex'
import loading from '@/components/loading'
import subscribe from '@/components/subscribe'
import { getQueryString } from '@/assets/js/common'

export default {
  name: 'app',
  components: {
    subscribe,
    loading,
    pageLoading
  },
  data () {
    return {
      hasLoadResources: false,
      routerAni: '',
      code: null,
      appid: null,
      state: null,
      subscribe: 1
    }
  },
  computed: mapState({
    isLoading: 'isLoading',
    activityGuid: 'activityGuid',
    userGuid: 'userGuid',
    userInfo: 'userInfo'
  }),
  created () {
    // 测试
    // this.getUserInfo()

    this.initResourcesLoader()

    if (sessionStorage.getItem('userGuid')) {
      this.getUserInfo()
    } else {
      this.code = getQueryString('code')
      this.appid = getQueryString('appid')
      this.state = getQueryString('state')
      if (!this.code) {
        window.location.href = this.$config.wx.link
      } else {
        this.getActivityGuid()
      }
    }
  },
  methods: {
    initResourcesLoader () {
      let loader = new Loader()
      const images = resources.images
      Object.keys(images).forEach(name => {
        console.log(name, images[name])
      })
      loader.onProgress.add(() => {
        console.log('progress>>>', loader.progress)
      })
      loader.onComplete.add(() => {
        setTimeout(() => {
          this.hasLoadResources = true
        }, 2500)
      })
      loader.load()
      window.loader = loader
    },
    getActivityGuid () {
      this.$http({
        method: 'post',
        url: `${this.$config.baseUrl}/api/stampactivity/opens`
      }).then(res => {
        if (+res.status === 1) {
          let activityGuid = res.data.activity_guid
          this.$store.commit('activityGuid', activityGuid)
          this.getOpenId(this.code, this.appid, this.state)
        } else {
          openToast({
            msg: res.message,
            duration: 3000
          })
        }
      })
    },
    getOpenId (code, appid, state) {
      this.$http({
        url: `${this.$config.comApiBase}/com/get_userinfo_by_code`,
        data: {
          code,
          appid,
          state
        }
      }).then(res => {
        this.$store.commit('userGuid', res.data.openid)
        sessionStorage.setItem('wxUserInfo', JSON.stringify(res.data.userinfo))
        this.getUserInfo()
      })
    },
    getUserInfo () {
      this.getSubscribe()
      this.$http({
        method: 'post',
        url: `${this.$config.baseUrl}/api/stampuser/details`,
        data: {
          activity_guid: this.activityGuid,
          user_guid: this.userGuid
        }
      }).then(res => {
        let data = res.data
        let userInfo = {}
        // let testUser = {
        //   'openid': 'oyxXov0MLnz22lEBNKv44Ys8bFSY',
        //   'nickname': '独木桥先生',
        //   'sex': 1,
        //   'language': 'zh_CN',
        //   'city': '武汉',
        //   'province': '湖北',
        //   'country': '中国',
        //   'headimgurl': 'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epDCenJhhlticz26Zu8JnByhuEViaT85NJ7FVjtyeZTscibgZ6lo0VvJlZK1YY0flZ4j4VRCgHibAFcsg/132',
        //   'privilege': []
        // }
        let wxUserInfo
        if (sessionStorage.getItem('wxUserInfo')) {
          wxUserInfo = JSON.parse(sessionStorage.getItem('wxUserInfo'))
        } else {
          // wxUserInfo = testUser
        }
        userInfo.userGuid = wxUserInfo.openid
        userInfo.nickname = wxUserInfo.nickname
        userInfo.headimgurl = wxUserInfo.headimgurl
        userInfo.phone = data['phone'] || ''
        userInfo.num_now = data['num_now'] > 8 ? 8 : data['num_now']
        userInfo.is_check = data['is_check'] || 0
        this.$store.commit('userInfo', userInfo)
      })
    },
    getSubscribe () {
      this.$http({
        url: `${this.$config.comApiBase}/com/get_user_info_by_openid`,
        data: {
          openid: this.userGuid,
          appid: this.$config.wx.appId
        }
      }).then(res => {
        if (+res.status === 1) {
          this.subscribe = res.data.subscribe
        }
      })
    }
  },
  watch: {
    '$route' (to, from) {
      const toPathLen = to.path.length
      const fromPathLen = from.path.length
      this.routerAni = toPathLen < fromPathLen ? 'slide-right' : 'slide-left'
    }
  }
}
</script>

<style lang="scss">
@import './assets/css/config';
#app{
  position:relative;
  width:100%;
  height:100%;
}
.router-view{
  // position: absolute;
  color:#FFF;
  position: fixed !important;
  transform-origin: 50% 50%;
  width:100%;
  height:100%;
  background-color:#20113d;
  transition: opacity .5s, transform .3s cubic-bezier(0.25,0.1,0.25,1);
}
.slide-left-enter{
  opacity:.5;
  transform: translate3d(100%, 0, 0);
}
.slide-left-leave-active {
  opacity:0;
  transform: translate3d(-33%, 0, 0);
}
.slide-right-enter {
  opacity:.5;
  transform: translate3d(-100%, 0, 0);
}
.slide-right-leave-active {
  opacity:0;
  transform: translate3d(33%, 0, 0);
}
</style>
